var express = require('express');
var router = express.Router();
let { userModel } = require('../model/model')
let { randomCode, sendCode } = require('./code')
//生成token包(npm i jsonwebtoken)
// var jwt = require("jsonwebtoken")
//腾讯人脸识别包(npm i tencentcloud-sdk-nodejs-iai)
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
//jwt
const jwt = require('jsonwebtoken')
const accessTokenSecret = 'your-access-token-secret';
const refreshTokenSecret = 'your-refresh-token-secret';

//人脸识别
router.get('/test', (req, res) => {
  res.send({
    code: 200,
    msg: 'success'
  })
})
//人脸识别登录
router.post('/faceLogin', async (req, res) => {
  //获取前端传来的base64
  let b64 = req.body.b64

  const IaiClient = tencentcloud.iai.v20200303.Client;

  const clientConfig = {
    credential: {
      //自己的腾讯secretId
      secretId: 'AKIDwocM8ucBobWODwiU7nUCzs94rWNWaf2T',
      //自己的腾讯密匙
      secretKey: 'UsNzcLycAoLi3Oak4RrNzc9mNuJdAqia',
    },
    region: "ap-beijing",  //地域参数（华北地区北京）
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  const client = new IaiClient(clientConfig);

  const params = {
    "GroupIds": [  //你创建的人员库ID
      "zjmshuai99"
    ],
    "Image": b64,  //图片的base64格式编码
    "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
    "QualityControl": 0,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
    "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
  };

  let doc = await client.SearchFaces(params)

  //doc为人脸识别后的返回信息
  console.log(doc, 'doc');

  if (doc.Results[0].Candidates.length != 0) {  //表示当前人脸库有该人员
    let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
    console.log(personName, 'personNume');

    //生成token
    let token = jwt.sign({ "name": personName }, "face", { expiresIn: '1d' })

    res.send({
      code: 200,
      msg: "登录成功！",
      token
    })

  } else {
    res.send({
      code: 401,
      msg: '人脸库无此人！'
    })
    return false
  }

})



//一键登录
router.post('/login_1', async function (req, res, next) {
  let { phone } = req.body
  let list = await userModel.find({ phone })
  if (list.length > 0) {
    res.send({
      code: 200,
      msg: '登录成功'
    })
  } else {
    await userModel.create({ phone })
    res.send({
      code: 200,
      msg: "登录成功！"
    })
  }
})



/* 登录并注册 */
router.post('/login', async function (req, res, next) {
  let { username, password, phone, code } = req.body
  let list = await userModel.find({ username, password, phone, code })
  if (list.length > 0) {
    const accessToken = jwt.sign({ username: username }, accessTokenSecret, { expiresIn: '30s' });
    const refreshToken = jwt.sign({ username: username }, refreshTokenSecret);
    res.send({
      code: 200,
      msg: '登录成功',
      accessToken,
      refreshToken
    })
  } else {
    if (username == '' || password == '' || phone == '' || code == '') {
      res.send({
        code: 400,
        msg: '请输入完整信息'
      })
    } else {
      await userModel.create({ username, password, phone, code })
      res.send({
        code: 200,
        msg: '注册成功'
      })
    }
  }
});

//获取验证码发送到手机上
//获取验证码接口
router.get("/code", async (req, res) => {
  let code = randomCode(4);//生成6位数字随机验证码
  sendCode(req.query.phone, code, function (success) {
    if (success) {
      res.send({
        code: 200,
        msg: "短信验证码发送成功",
        codes: code
      });
    } else {
      res.send("短信验证码发送失败");
    }
  })
})

//修改密码
router.post('/updatepwd', async function (req, res, next) {
  let ls = req.body
  console.log(ls);

  await userModel.updateOne({ phone: ls.phone }, ls)
  res.send({
    code: 200,
    msg: '修改成功',
  })
})



module.exports = router;
